<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad"
               @sort-change="sortChange"
               @date-change="dateChange">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.port_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot="menu" slot-scope="{row,index,size,type}">
        <el-button
          v-if="permission.port_pass"
          icon="el-icon-circle-check"
          plain
          @click="passPort(row, index)"
          :size="size"
          :type="type">通过
        </el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, passPort} from "@/api/desk/port";
  import {mapGetters} from "vuex";

  export default {
    data() {

      return {
        form: {},
        query: {
          descs: 'update_time',
        },
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          // menuWidth: 250,
          defaultSort: {
            prop: 'createTime',
            order: 'descending'
          },
          // title:'表格的标题',//导出表格的标题
          excelBtn: true,//是否导出
          filterBtn: true,

          // dateBtn:true,//日期
          height: 'auto',
          calcHeight: 230,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          border: true,
          index: true,
          indexLabel: '序号',
          viewBtn: true,
          // delBtn: true,
          // editBtn: false,
          selection: true,//搜索框
          align: 'center',//居中
          stripe: true,//斑马纹
          dialogDrag: true,//弹框课拖拽
          column: [
            {
              label: "服务器ip",
              prop: "ip",
              search: true,
              searchOrder: 1,
              filterable: true,
              viewDisplay: false,
              rules: [{
                required: true,
                message: "请输入服务器ip",
                trigger: "blur"
              }]
            },
            {
              label: "端口",
              prop: "port",
              width: 100,
              type: "number",
              search: true,
              searchOrder: 2,
              viewDisplay: false,
              rules: [{
                required: true,
                message: "请输入开通的端口",
                trigger: "blur"
              }]
            },
            {
              label: "映射类型",
              prop: "mappingType",
              width: 100,
              type: 'select',
              viewDisplay: false,
              dicData: [
                {
                  label: 'web映射',
                  value: 'web'
                },
                {
                  label: 'tcp映射',
                  value: 'tcp'
                }
              ],
              rules: [{
                required: true,
                message: "请输入映射类型:web or tcp",
                trigger: "blur"
              }],

            },
            {
              label: "映射名称",
              prop: "mappingName",
              search: true,
              searchOrder: 3,
              // sortable: true,
              minWidth: 100,
              addDisplay: false,
              editDisplay: false,
              // viewDisplay: false,
              rules: [{
                required: true,
                message: "请输入映射名称",
                trigger: "blur"
              }]
            },
            {
              label: "映射路径",
              prop: "mappingUrl",
              minWidth: 100,
              // prepend:'http://',
              // append:'.net',
              // display: true
              rules: [{
                required: true,
                message: "请输入映射路径",
                trigger: "blur"
              }]
            },
            {
              label: "所属用户",
              prop: "userName",
              // hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              rules: [{
                required: true,
                message: "请输入创建人",
                trigger: "blur"
              }]
            },
            {
              label: "创建时间",
              prop: "createTime",
              // sortable: true,
              // searchOrder:1,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              rules: [{
                required: true,
                message: "请输入创建时间",
                trigger: "blur"
              }]
            },
            {
              label: "端口状态",
              prop: "status",
              width: 100,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }],
              dicData: [
                {
                  label: '已开通',
                  value: 1
                },
                {
                  label: '待审核',
                  value: 0
                }
              ],
            },
            {
              label: "执行脚本",
              prop: "script",
              type: 'textarea',
              minRows: 20,
              // maxlength:200,
              span: 24,
              hide: true,
              addDisplay: false,
              editDisplay: false,
              // viewDisplay: false,
              rules: [{
                required: true,
                message: "请输入执行脚本",
                trigger: "blur"
              }]
            },
            // {
            //   label: "用户邮箱",
            //   prop: "userEmail",
            //   hide: true,
            //   addDisplay: false,
            //   editDisplay: false,
            //   viewDisplay: false,
            //   rules: [{
            //     required: true,
            //     message: "请输入创建人email",
            //     trigger: "blur"
            //   }]
            // },
            // {
            //   label: "id",
            //   prop: "id",
            //   hide: true,
            //   addDisplay: false,
            //   editDisplay: false,
            //   viewDisplay: false
            // },
            // {
            //   label: "创建人id",
            //   prop: "createUser",
            //   rules: [{
            //     required: true,
            //     message: "请输入创建人",
            //     trigger: "blur"
            //   }]
            // },
            // {
            //   label: "修改人",
            //   prop: "updateUser",
            //   rules: [{
            //     required: true,
            //     message: "请输入修改人",
            //     trigger: "blur"
            //   }]
            // },
            // {
            //   label: "修改时间",
            //   prop: "updateTime",
            //   rules: [{
            //     required: true,
            //     message: "请输入修改时间",
            //     trigger: "blur"
            //   }]
            // },
            // {
            //   label: "",
            //   prop: "isDeleted",
            //   rules: [{
            //     required: true,
            //     message: "请输入",
            //     trigger: "blur"
            //   }]
            // },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.port_add, false),
          viewBtn: this.vaildData(this.permission.port_view, false),
          delBtn: this.vaildData(this.permission.port_delete, false),
          editBtn: this.vaildData(this.permission.port_edit, false),
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },

    methods: {

      // dateChange(date){
      //   this.$message.success(JSON.stringify(date));
      // },
      sortChange(val) {
        this.defaultSort = val;
      },
      passPort(row) {
        passPort(row.id).then(res => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: res.data.msg,
          });
        }, error => {
          window.console.log(error);
        });
      },
      rowSave(row, done, loading) {
        add(row).then(res => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: res.data.msg,
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(res => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: res.data.msg,
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(res => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: res.data.msg,
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(res => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: res.data.msg,
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    },

    watch: {
      'form.mappingType': {
        handler(val) {
          //域名效验方法
          const validateDomain = (rule, value, callback) => {
            if (value !== '') {
              const re = new RegExp("[a-zA-Z0-9_-]{1,62}(\\.[a-zA-Z0-9_-]{1,62}){0,2}"+'$');
              if (!re.test(value)) {
                callback(new Error('自定义域名只能包含 a-z, A-Z, 0-9, ".", "_", "-"'));
              }else {
                callback();
              }
            }
            callback();
          };
          const mappingUrl = this.findObject(this.option.column, 'mappingUrl')
          if (val === "web") {
            mappingUrl.display = true
            mappingUrl.rules = [{validator: validateDomain, trigger: 'blur'}]
          } else {
            mappingUrl.display = false
            mappingUrl.rules = []
          }
        },
        immediate: true
      },
    },
  };
</script>

<style>
</style>
